import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:nft_shop/login/controller/logic_controller.dart';
import 'package:nft_shop/login/controller/user_controller.dart';
import 'package:nft_shop/my/model/models.dart';
import 'package:nft_shop/my/page/wallet/my_record_page.dart';
import 'package:nft_shop/my/page/wallet/my_wallet_details.dart';
import 'package:nft_shop/my/page/wallet/my_withdraw_page.dart';
import 'package:nft_shop/my/view/album_hint.dart';
import 'package:nft_shop/net/service_repository.dart';
import 'package:nft_shop/res/constant.dart';
import 'package:nft_shop/res/global.dart';
import 'package:nft_shop/util/other_utils.dart';
import 'package:nft_shop/util/route_observer.dart';
import 'package:nft_shop/widgets/load_image.dart';
import 'package:nft_shop/widgets/my_app_bar.dart';
import 'package:nft_shop/widgets/my_scroll_view.dart';
import 'package:nft_shop/widgets/status_view.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class MyWalletPage extends StatefulWidget {
  const MyWalletPage({Key? key}) : super(key: key);

  @override
  _MyWalletPageState createState() => _MyWalletPageState();
}

class _MyWalletPageState extends State<MyWalletPage>
    with
        SingleTickerProviderStateMixin,
        AutomaticKeepAliveClientMixin,
        RouteAware {
  /// 分页第一页页码
  static const int pageNumFirst = 1;

  /// 当前第几页
  int currentPageNum = pageNumFirst;

  /// 分页条目数量
  int pageSize = 10;

  /// 页面数据
  List list = [];

  ///状态
  int _status = LoadStatusType.loading;

  bool isShow = true;

  ///刷新组件
  RefreshController refreshController =
      RefreshController(initialRefresh: false);

  int get status => _status;

  set status(int value) {
    _status = value;
    setState(() {});
  }

  @override
  bool get wantKeepAlive => true;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    RouteUtils.routeObserver
        .subscribe(this, ModalRoute.of(context) as PageRoute);
  }

  @override
  void dispose() {
    RouteUtils.routeObserver.unsubscribe(this);
    super.dispose();
  }

//回到当前页面
  @override
  void didPopNext() {
    refresh();
    print("盲盒返回刷新了---");
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    refresh();
  }

  //获取数据
  Future<List> loadData({int? pageNum}) async {
    return await ServiceRepository.billList(
        page: pageNum!, pageSize: pageSize, type: 0);
  }

  /// 下拉刷新
  ///
  /// [init] 是否是第一次加载
  /// true:  Error时,需要跳转页面
  /// false: Error时,不需要跳转页面,直接给出提示
  Future<List?> refresh({bool init = false}) async {
    try {
      LoginLogic.to.getUserInfoData();
      currentPageNum = pageNumFirst;
      var data = await loadData(pageNum: pageNumFirst);
      if (data.isEmpty) {
        refreshController.refreshCompleted(resetFooterState: true);
        list.clear();
        status = LoadStatusType.empty;
      } else {
        list.clear();
        list.addAll(data);
        refreshController.refreshCompleted();
        // 小于分页的数量,禁止上拉加载更多
        if (data.length < pageSize) {
          // refreshController.loadNoData();
        } else {
          //防止上次上拉加载更多失败,需要重置状态
          refreshController.loadComplete();
        }
        status = LoadStatusType.success;
      }
      return data;
    } catch (e, s) {
      /// 页面已经加载了数据,如果刷新报错,不应该直接跳转错误页面
      /// 而是显示之前的页面数据.给出错误提示
      if (init) list.clear();
      refreshController.refreshFailed();
      status = LoadStatusType.empty;
      // setError(e, s);
      return null;
    }
  }

  /// 上拉加载更多
  Future<List?> loadMore() async {
    try {
      var data = await loadData(pageNum: ++currentPageNum);
      if (data.isEmpty) {
        currentPageNum--;
        refreshController.loadNoData();
      } else {
        list.addAll(data);
        if (data.length < pageSize) {
          refreshController.loadNoData();
        } else {
          refreshController.loadComplete();
        }
        setState(() {});
      }
      return data;
    } catch (e, s) {
      currentPageNum--;
      refreshController.loadFailed();
      return null;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        centerTitle: "钱包",
      ),
      body: Column(
        children: [
          _topView(),
          _allView(),
          Expanded(
            child: _listViewWidget(),
          )
        ],
      ),
    );
  }

  Widget _listViewWidget() {
    return SmartRefresher(
      controller: refreshController,
      header: WaterDropHeader(),
      footer: ClassicFooter(),
      onRefresh: refresh,
      onLoading: loadMore,
      enablePullUp: true,
      child: _buildListView(),
    );
  }

  _buildListView() {
    if (status != LoadStatusType.success) {
      return StatusViews(status);
    }
    return ListView.builder(
      itemCount: list.length,
      itemBuilder: (_, index) {
        return _buildItem(index);
      },
    );
  }

  //item
  _buildItem(int index) {
    BillListModel model = list[index];
    return InkWell(
      onTap: () => Get.to(MyWalletDetailsPage(
        model: model,
      )),
      child: Container(
        height: 70,
        margin: EdgeInsets.symmetric(horizontal: 15),
        decoration: BoxDecoration(
            border: Border(
          bottom: Divider.createBorderSide(context,
              color: Global.kTheme.colorLine, width: 1),
        )),
        child: Column(
          children: [
            Padding(
              padding: const EdgeInsets.only(
                top: 14,
              ),
              child: Row(
                children: [
                  Text(
                    model.title ?? "",
                    style: TextStyle(
                        fontSize: 14,
                        color: Global.kTheme.textPrimary6,
                        fontFamily: Global.mySemiboldFont),
                  ),
                  Spacer(),
                  Text(
                    model.turnover ?? "0.00",
                    style: TextStyle(
                        fontSize: 14,
                        color: Global.kTheme.textPrimary6,
                        fontFamily: Global.mySemiboldFont),
                  )
                ],
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(
                top: 5,
              ),
              child: Row(
                children: [
                  Text(
                    model.createTime ?? "",
                    style: TextStyle(
                        fontSize: 11,
                        color: Global.kTheme.inputHint1,
                        fontFamily: Global.mySemiboldFont),
                  ),
                  Spacer(),
                  Text(
                    "余额 ${model.moneyProof}",
                    style: TextStyle(
                        fontSize: 11,
                        color: Global.kTheme.inputHint1,
                        fontFamily: Global.mySemiboldFont),
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  //topView
  Widget _topView() {
    return Container(
      height: 120,
      margin: EdgeInsets.symmetric(
        horizontal: 15,
      ),
      padding: EdgeInsets.only(top: 5),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8),
        gradient: LinearGradient(colors: [
          Color(0xFF474747),
          Color(0xFF222222),
        ], begin: Alignment.topCenter, end: Alignment.bottomCenter),
      ),
      child: Row(
        children: [
          GetBuilder<UserController>(
              id: UserController.UserInfo,
              builder: (logic) {
                return Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    InkWell(
                      onTap: () {
                        setState(() {
                          isShow = !isShow;
                        });
                      },
                      child: Container(
                        padding: EdgeInsets.only(left: 25, top: 30),
                        child: Text.rich(
                          TextSpan(children: [
                            TextSpan(
                                text: "可提现金额(¥)",
                                style: TextStyle(
                                    fontSize: 12,
                                    color: Global.kTheme.textPrimary5)),
                            WidgetSpan(
                                child: SizedBox(
                              width: 7,
                            )),
                            WidgetSpan(
                                child: Center(
                                    child: LoadAssetImage(
                              isShow ? "eye_open" : "eye_close",
                              height: 11,
                            ))),
                          ]),
                          textAlign: TextAlign.center,
                        ),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(left: 25, top: 10),
                      child: Text(
                        isShow ? logic.member.money ?? "0.00" : "****",
                        style: TextStyle(
                            fontSize: 24, color: Global.kTheme.textPrimary5),
                      ),
                    ),
                  ],
                );
              }),
          Spacer(),
          InkWell(
            onTap: () async {
              try {
                EasyLoading.show(status: "加载中");
                MemberExtendModel model =
                    await ServiceRepository.memberExtend();
                EasyLoading.dismiss();
                if (model.alipayAccount!.length == 0) {
                  Utils.showElasticDialog<void>(
                    context: context,
                    barrierDismissible: false,
                    builder: (BuildContext context) {
                      return CollectionDialog();
                    },
                  );
                } else {
                  EasyLoading.dismiss();
                  Get.to(MyWithdrawPage(
                    alipayAccount: model.alipayAccount!,
                  ));
                }
              } catch (e, s) {
                EasyLoading.dismiss();
              }
            },
            child: Container(
              width: 118,
              height: 38,
              decoration: BoxDecoration(
                color: Color(0xFF505050),
                borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(19),
                    bottomLeft: Radius.circular(19)),
              ),
              child: Center(
                child: Text(
                  "提现",
                  style: TextStyle(
                      fontSize: 14,
                      color: Global.kTheme.textPrimary5,
                      fontFamily: Global.mySemiboldFont),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  //全部
  Widget _allView() {
    return InkWell(
      onTap: () => Get.to(MyRecordPage()),
      child: Container(
        height: 60,
        margin: EdgeInsets.symmetric(horizontal: 15),
        decoration: BoxDecoration(
            border: Border(
          bottom: Divider.createBorderSide(context,
              color: Global.kTheme.colorLine, width: 1),
        )),
        child: Row(
          children: [
            Text(
              "余额变动明细",
              style: TextStyle(
                  fontSize: 14,
                  color: Global.kTheme.inputHint1,
                  fontFamily: Global.mySemiboldFont),
            ),
            Spacer(),
            Text(
              "全部",
              style: TextStyle(
                  fontSize: 12,
                  color: Global.kTheme.inputHint1,
                  fontFamily: Global.mySemiboldFont),
            ),
            SizedBox(
              width: 5,
            ),
            LoadAssetImage(
              "next_icon",
              width: 7,
              height: 12,
            )
          ],
        ),
      ),
    );
  }
}
